package com.eshop.utils;

import com.eshop.exception.BadRequestException;
import javax.validation.ConstraintViolationException;
import java.io.Writer;
import java.io.PrintWriter;
import java.io.StringWriter;

public class ThrowableUtil
{
    public static String getStackTrace(final Throwable throwable) {
        final StringWriter sw = new StringWriter();
        try (final PrintWriter pw = new PrintWriter(sw)) {
            throwable.printStackTrace(pw);
            return sw.toString();
        }
    }
    
    public static void throwForeignKeyException(final Throwable e, final String msg) {
        Throwable t;
        for (t = e.getCause(); t != null && !(t instanceof ConstraintViolationException); t = t.getCause()) {}
        if (t != null) {
            throw new BadRequestException(msg);
        }
        assert false;
        throw new BadRequestException("删除失败：" + t.getMessage());
    }
}
